﻿#include "DMCreator.h"
#include <QDebug>
DMCreator::DMCreator()
{

}

bool DMCreator::encodeString8Bit(QString str)
{
    if(m_enc)
    {
        dmtxEncodeDestroy(&m_enc);
    }
    m_enc = dmtxEncodeCreate();
    assert(m_enc != NULL);
    dmtxEncodeSetProp(m_enc, DmtxPropBytesPerPixel, 1);
//    dmtxEncodeDataMosaic(m_enc, str.length(), (unsigned char *)str.toLocal8Bit().data());
    dmtxEncodeDataMatrix(m_enc, str.length(), (unsigned char *)str.toLocal8Bit().data());
    return true;
}

bool DMCreator::encodeString(QString str)
{
    if(m_enc)
    {
        dmtxEncodeDestroy(&m_enc);
    }
    m_enc = dmtxEncodeCreate();
    assert(m_enc != NULL);
    dmtxEncodeSetProp(m_enc, DmtxPropBytesPerPixel, 1);
    QByteArray ba = str.toUtf8();
    dmtxEncodeDataMatrix(m_enc, ba.size(), (unsigned char *)ba.data());
    //dmtxEncodeDataMatrix(m_enc, ba.size(), (unsigned char *)ba.data());
    return true;
}

bool DMCreator::isValid() const
{
    if(!m_enc) return false;
    return true;
}

bool DMCreator::renderNoBackground(QPainter &painter, QRect rect) const
{
    if(!isValid()) return false;

    int width = dmtxImageGetProp(m_enc->image, DmtxPropWidth);
    int height = dmtxImageGetProp(m_enc->image, DmtxPropHeight);
    if(rect.isNull())
    {
        rect.setRect(0, 0, width * 4, height * 4);
    }
    const double offset_x = rect.left();
    const double offset_y = rect.top();
    const double scale_x = static_cast<double>(rect.width()) / width;
    const double scale_y = static_cast<double>(rect.height()) / height;

    int rowSizeBytes = m_enc->image->rowSizeBytes;
    int bytesPerPixel = m_enc->image->bytesPerPixel;
    for( int y = 0; y < height; y ++)
    {
        for(int x = 0; x < width; x ++)
        {
            unsigned char b = m_enc->image->pxl[y * rowSizeBytes  + x * bytesPerPixel];
            if(b == 0)
            {
                QRectF r(offset_x + x * scale_x, offset_y + y * scale_y, scale_x, scale_y);
                painter.drawRect(r);
            }
        }
    }
    return true;
}

QSize DMCreator::size()  const
{
    if(!isValid()) return QSize(0, 0);
    int width = dmtxImageGetProp(m_enc->image, DmtxPropWidth);
    int height = dmtxImageGetProp(m_enc->image, DmtxPropHeight);

    return QSize(width, height);
}




